<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 创建全局中间订阅者 Watch
      let Watch = null
      // 创建vue的构造函数
      function Vue({ data }) {
        this._data = data
        // 为了方便使用,会在vm实例中创建一份数据拷贝,方便调用,但是需要修改其值时_data中会跟随改变,获取其时必须使用_data中的最新值
        // 所以就需要使用数据存取器object.defineProperty()对多个数据进行监视
        // 数据存储器
        for (const key in data) {
          Object.defineProperty(this, key, {
            get() {
              return this._data[key]
            },
            set(value) {
              this._data[key] = value
            },
          })
        }
        new Publish(this._data)
      }

      class Publish {
        constructor(obj) {
          this.reserve(obj)
        }
        reserve(obj) {
          for (const key in obj) {
            if (typeof obj[key] === 'object' && obj[key] !== null) {
              new Publish(obj[key])
            }
            this.definePro(obj, key)
          }
        }
        definePro(obj, key) {
          let value = obj[key]
          let dep = new Dep()
          Object.defineProperty(obj, key, {
            get() {
              console.log(Watch)
              if (Watch !== null) {
                dep.depend(Watch)
              }
              console.log('获取捕获')
              return value
            },

            set(val) {
              if (val === value) return
              console.log('设置捕获')
              value = val
              dep.promulgate()
            },
          })
        }
      }

      class Dep {
        constructor() {
          this.watchers = []
        }
        depend(watcher) {
          this.watchers.push(watcher)
        }
        promulgate() {
          console.log('该获取数据了')
          this.watchers.forEach((item) => {
            item.updata()
          })
        }
      }
      class Subscriber {
        // 订阅的数据
        constructor(data, key) {
          this.data = data
          this.key = key
          Watch = this
          this.geter()
          Watch = null
        }
        geter() {
          return this.data[this.key]
        }
        updata() {
          console.log('数据更新,新数据为' + this.geter())
        }
      }

      function observe() {}
      let vm = new Vue({
        data: {
          name: '张三',
          age: 18,
          obj: {
            sex: '男',
            age: 18,
          },
        },
      })
      new Subscriber(vm.obj, 'sex')
      // vm.name = 'ss'
    </script>
  </body>
</html>
